import _ from 'lodash'
import moment from 'moment'
import NP from 'number-precision'

import {
  ROUTER_MAP,
  getSeriesForLineTypeTwo,
  getSeriesForPast,
  getMoneyText,
  getMantissa,
  getMacauNextDay
} from '@/utils/study.js'

import { groupMapBySize } from '@/data/index.js'

// 定义魔法数字常量
const VALUE_RED = 0
const VALUE_GREEN = 10

// 计算 arbitrary 模块的统计数据
const calcArbitrary = (store) => {
  const { allValues } = store.state.study
  // 将所有分组映射扁平化为一个单一对象
  const flattenedGroupMap = Object.assign({}, ...Object.values(groupMapBySize))
  // console.log('flattenedGroupMap', flattenedGroupMap) // key 是对应数值的所有分组字符串名称, value 是对应分组数据

  // 提取每种组大小对应的分组选项
  const groupOptions = Object.entries(groupMapBySize).reduce((acc, [size, groups]) => {
    acc[size] = Object.keys(groups)
    return acc
  }, {})

  // console.log('groupOptions', groupOptions) // key 是英文数值, value 是对应数值的所有分组字符串名称数组

  // 初始化结果数组
  const results = {
    redContinuousMax: [],
    greenRebound: [],
    greenContinuous: []
  }

  // console.log('Object.entries(groupOptions)', Object.entries(groupOptions))

  const entriesGroupOptions = Object.entries(groupOptions) // 数组: first 是英文数值, last 是对应数值的所有分组字符串名称数组

  // 遍历每种组大小及其对应的分组
  entriesGroupOptions.forEach(([sizeKey, groups]) => {
    groups.forEach((groupName) => {
      const groupData = flattenedGroupMap[groupName]
      const processedValues = getSeriesForLineTypeTwo(allValues, groupData)

      // 获取最后两个元素
      const [secondLast, last] = processedValues.slice(-2)
      const lastRed = BigInt(last.valueCount[VALUE_RED])
      const lastGreen = BigInt(last.valueCount[VALUE_GREEN])

      // console.log('lastRed', lastRed.toString())
      // console.log('lastGreen', lastGreen.toString())

      // 计算总数并验证
      const totalCount = lastRed + lastGreen
      if (totalCount === 0n) {
        console.warn('Total count is zero, skipping calculation for group:', groupName)
        return
      }

      // 计算正确率
      const accuracyRate = Number((lastGreen * 100n) / totalCount).toFixed(2)

      // 创建最后一项对象
      const lastItem = {
        group: groupName,
        router: ROUTER_MAP[groupName],
        last,
        groupsNumber: last.groupsNumber,
        maxCountError: last.maxWrongStreak,
        accuracyRate
      }

      // 根据最后两个值确定描述
      if (last.value === VALUE_RED && secondLast.value === VALUE_RED) {
        lastItem.a_desc = '预测红色连续不超过2次'
        results.redContinuousMax.push(lastItem)
      } else if (last.value === VALUE_RED && secondLast.value === VALUE_GREEN) {
        lastItem.a_desc = '预测绿色回弹，红色不连续'
        results.greenRebound.push(lastItem)
      } else if (last.value === VALUE_GREEN && secondLast.value === VALUE_RED) {
        lastItem.a_desc = '预测绿色连续'
        results.greenContinuous.push(lastItem)
      }
    })
  })

  // 定义排序函数：先按 accuracyRate 降序，再按 maxCountError 升序
  const sortResults = (a, b) => {
    if (b.accuracyRate !== a.accuracyRate) {
      return b.accuracyRate - a.accuracyRate // accuracyRate 降序
    }
    return a.maxCountError - b.maxCountError // maxCountError 升序
  }

  // 对结果数组进行排序
  results.redContinuousMax.sort(sortResults)
  results.greenRebound.sort(sortResults)
  results.greenContinuous.sort(sortResults)

  // 统一打印所有结果，便于调试和查看
  // console.log('红色连续不超过2次:', results.redContinuousMax)
  // console.log('绿色回弹，红色不连续:', results.greenRebound)
  // console.log('绿色连续:', results.greenContinuous)
  return results
}

// 计算 past  模块的统计数据
const calcPast = (store, _selectValue) => {
  const { allValues } = store.state.study
  const past_results = getSeriesForPast(allValues, _selectValue)
  const last_item = past_results[past_results.length - 1]
  const result = _.cloneDeep(last_item.recentValues)
  result.push(last_item.sourceData.number)
  return result
}

/**
 * 处理控制台输出
 * @param {string} nextDay - 下期日期
 * @param {object} arbitrary_results - 任意模块的统计数据
 * @param {object} last_item - 最后一条数据
 */
const handleConsole = (nextDay, arbitrary_results, last_item, past_results, label) => {
  const text = `
  ${label}

  ${nextDay}
	TODO：
	${getMoneyText(arbitrary_results.redContinuousMax, '红色连续不超过2次')}

	${getMoneyText(arbitrary_results.greenRebound, '绿色回弹，红色不连续')}

	${getMoneyText(arbitrary_results.greenContinuous, '绿色连续')}

  kill mantissa:
    [
      ${getMantissa(last_item.number).join(',')}
    ]

  前${past_results.length}期：
    [
      ${past_results.join(',')}
    ]

  kill all：
    [

    ]
  `
  // console.clear()
  console.log(text)
}

// 获取香港下一期
const getHongKongNextDay = async () => {
  const fetchWithFallback = async (url, fallbackUrl) => {
    try {
      const response = await fetch(url)
      // console.log('response', response)
      if (!response.ok) throw new Error('Failed to fetch primary URL')
      const { data } = await response.json()
      return moment(data.six.next.awardTime, 'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD')
    } catch (error) {
      const fallbackResponse = await fetch(fallbackUrl)
      if (!fallbackResponse.ok) throw new Error('Failed to fetch fallback URL')
      const { data } = await fallbackResponse.json()
      return moment(data.six.next.awardTime, 'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD')
    }
  }

  return fetchWithFallback('//hk-marksix.com/111api/lottery/info/six', '//marksixlottery.net/api/lottery/info/six')
}

// 初始化
const init = async (store) => {
  if (store.state.study.allValues.length === 0) {
    return
  }
  const region = store.state.study.region
  // 获取下期日期
  let nextDay

  // alert(store.state.study.region)

  const label = region === 'm' ? '澳门' : '香港'

  // console.log(store.state.study.region)
  // 获取最后一条数据
  const last_item = _.get(store, 'state.study.allValues').slice(-1)[0]

  // 获取下期日期
  if (region === 'm') {
    nextDay = getMacauNextDay(last_item.time)
  } else {
    nextDay = await getHongKongNextDay()
  }

  // console.log('nextDay', nextDay)

  // 计算任意模块的统计数据
  const arbitrary_results = calcArbitrary(store)

  // 计算 Past 模块的统计数据
  const past_results = calcPast(store, 10)

  // 处理控制台输出
  handleConsole(nextDay, arbitrary_results, last_item, past_results, label)
}

export default (store) => {
  // init(store)
}
